package com.dnjn.happiness.biz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.biz.domain.Appraise;
import com.dnjn.happiness.biz.domain.AppraiseTags;
import com.dnjn.happiness.biz.domain.AppraiseXref;
import com.dnjn.happiness.biz.domain.vo.AppraiseGradeEnum;
import com.dnjn.happiness.biz.domain.vo.AppraiseGradeIntEnum;
import com.dnjn.happiness.biz.domain.vo.StatisticalAnalysisAppriseVO;
import com.dnjn.happiness.biz.domain.vo.StatisticalAnalysisVO;
import com.dnjn.happiness.biz.mapper.AppraiseMapper;
import com.dnjn.happiness.biz.mapper.AppraiseXrefMapper;
import com.dnjn.happiness.biz.service.IAppraiseService;
import com.dnjn.happiness.biz.service.IAppraiseTagsService;
import com.dnjn.happiness.common.amqp.AmqpSender;
import com.dnjn.happiness.common.core.constant.HappyConstants;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.model.ModelHappinessScores;
import com.dnjn.happiness.common.core.utils.DateUtils;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.datascope.annotation.DataScope;
import com.dnjn.happiness.common.core.score.vo.HappyApprise;
import com.dnjn.happiness.common.core.score.vo.HappyVO;
import com.dnjn.happiness.system.api.RemoteTeamService;
import com.dnjn.happiness.system.api.domain.SysTeam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 评价表 服务实现类
 * </p>
 *
 * @author Amber
 * @since 2023-10-04
 */
@Service
public class AppraiseServiceImpl extends ServiceImpl<AppraiseMapper, Appraise> implements IAppraiseService {

    @Autowired
    private AppraiseXrefMapper xrefMapper;

    @Autowired
    private IAppraiseTagsService appraiseTagsService;

    

    @Autowired
    private RemoteTeamService sysTeamService;

    @Override
    public List<ModelHappinessScores> getAppraiseHappinessScores(Long userId, String tableName) {
        List<ModelHappinessScores> list = baseMapper.getAppraiseHappinessScores(userId, tableName);
        return list;

    }

    @Override
    @DataScope(deptAlias = "u")
    public Page<Appraise> selectPageX(Appraise appraise, Page page) {
        return baseMapper.selectPageX(appraise, page);
    }

    @Override
    public List<StatisticalAnalysisVO> AnalysisPage(Page<Object> happiness_score) {
        return baseMapper.AnalysisPage(happiness_score);
    }

    @Override
    public List<StatisticalAnalysisVO> ListPageSerch(StatisticalAnalysisAppriseVO vo, Page<Object> happiness_score) {
        return null;
    }


    @Override
    public List<StatisticalAnalysisVO> ListPageSerchX(StatisticalAnalysisAppriseVO vo, Page<Object> happiness_score) {
        return baseMapper.ListPageSerchX(vo, happiness_score);
    }

    @Override
    public Double getHappinessScoresViewAppriseNew(Long userId, Double base_percent, Double x) {
        return baseMapper.getHappinessScoresViewAppriseNew(userId, base_percent, x);
    }


    @Override
    public Page<StatisticalAnalysisVO> selectStatisticalAnalysisApprise(StatisticalAnalysisAppriseVO vo, Page page) {
        return baseMapper.selectStatisticalAnalysisApprise(vo, page);
    }

    @Override
    public Page<Appraise> getAppraisePageByFromUserId(Appraise domain, Page page) {
        Page<Appraise> appraisePage = baseMapper.getAppraisePageByFromUserId(domain, page);
        List<AppraiseTags> list = appraiseTagsService.lambdaQuery().eq(AppraiseTags::getDeleted, "0").eq(AppraiseTags::getActive, 'Y').list();

        for (Appraise dto : appraisePage.getRecords()) {
            List<AppraiseXref> appraiseXrefs = xrefMapper.selectItems(dto);
            List<Long> tagIdList = appraiseXrefs.stream().map(AppraiseXref::getTagId).collect(Collectors.toList());
            list.forEach(item -> {
                if (!tagIdList.contains(item.getAppraiseTagsId())) {
                    AppraiseXref xref = new AppraiseXref();
                    xref.setGrade("无");
                    xref.setLabel(item.getLabel());
                    appraiseXrefs.add(xref);
                }
            });
            dto.setXrefList(appraiseXrefs);
        }
        return appraisePage;
    }

    @Override
    public List<Appraise> queryAppraiseListByUserId(Appraise appraise) {
        List<Appraise> list = baseMapper.queryAppraiseListByUserId(appraise);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                List<AppraiseXref> xrefList = xrefMapper.selectItems(item);
                item.setXrefList(xrefList);
                Long parentId = null;
                SysTeam parentTeam = null;
                R<SysTeam> result = sysTeamService.getParentInfoByUserId(item.getUserId(), SecurityConstants.INNER);
                if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
                    parentTeam = result.getData();
                    parentId = result.getData().getTeamId();
                }
                if (null != parentId && !Objects.isNull(parentTeam)) {
                    String sysTeamName = parentTeam.getNickName();
                    item.setSysTeamName(sysTeamName);
                }
            });
        }
        return list;
    }

    @Override
    public Page<Appraise> selectPageNew(Appraise appraise, Page page) {

        // 查询当前团队下边的人
        if (ObjectUtil.isNotNull(appraise.getTeamId())) {
            R<List<Long>> result = sysTeamService.getChildList(appraise.getTeamId(), SecurityConstants.INNER);
            if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
                appraise.setTeamUserIds(result.getData());
            }

          /*  List<SysTeam> list = new ArrayList<>();
            getChildList(appraise.getTeamId(), list);
            List<Long> collect = list.stream().map(SysTeam::getUserId).collect(Collectors.toList());
            if (null != collect && collect.size() > 0) {
                appraise.setTeamUserIds(collect);
            }*/

        }

        Page<Appraise> appraisePage = baseMapper.selectPageNew(appraise, page);
        List<Appraise> records = appraisePage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (Appraise item : records) {
                List<AppraiseXref> xrefList = xrefMapper.selectItems(item);
                item.setXrefList(xrefList);
                SysTeam sysTeam = null;
                R<SysTeam> result = sysTeamService.getInfoById(item.getUserId(), SecurityConstants.INNER);
                if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
                    sysTeam = result.getData();
                }
                if (Objects.isNull(sysTeam) || Objects.isNull(sysTeam.getParentId())) {
                    continue;
                }
                SysTeam parentTeam = null;
                R<SysTeam> parentTeamResult = sysTeamService.queryInfoByTeamId(sysTeam.getParentId(), SecurityConstants.INNER);
                if (StringUtils.isNotNull(parentTeamResult) && StringUtils.isNotNull(parentTeamResult)){
                    parentTeam = parentTeamResult.getData();
                }
                if (Objects.isNull(parentTeam)) {
                    continue;
                }
                item.setSysTeamName(parentTeam.getNickName());
            }
        }
        return appraisePage;
    }

   /* public void getChildList(Long teamId, List<SysTeam> list) {
        List<SysTeam> childList = sysTeamMapper.selectList(Wrappers.lambdaQuery(SysTeam.class).eq(SysTeam::getParentId, teamId));
        if (childList.size() > 0) {
            for (SysTeam child : childList) {
                list.add(child);
                getChildList(child.getTeamId(), list);

            }
        }
    }*/

    @Override
    public boolean addAppraiseNew(Appraise appraise) {


        List<AppraiseXref> xrefList = appraise.getXrefList();
        float grade = 0L;
        float count = (xrefList.size());

        for (AppraiseXref item : xrefList) {
            Integer score = AppraiseGradeEnum.getScore(item.getGrade());
            grade += score;
        }
        Integer AppraiseGrade = Math.round((grade / count));//算等级

        appraise.setLikeCounts(AppraiseGrade);
        appraise.setGrade(AppraiseGradeIntEnum.getType(AppraiseGrade));
        baseMapper.insert(appraise);

        for (AppraiseXref item : xrefList) {
            item.setAppraiseId(appraise.getAppraiseId());
            xrefMapper.insert(item);
        }
        //todo 更新时间
        Date nowDate = DateUtils.getNowDate();

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(now);
        sysTeamService.updateAppraiseTime(appraise.getUserId(),SecurityConstants.INNER);

        // todo 后台-新增评价-评价改版
        HappyVO happyVO = new HappyVO();
        happyVO.setUserId(appraise.getUserId());
        HappyApprise happyApprise = new HappyApprise();
        happyApprise.setLikeCount(appraise.getLikeCounts());
//        appraise.setUserId(appraise.getUserId());
        happyVO.setRtype(HappyConstants.EMO_USER_RTYPE_APPRAISE);// 根据类型查权重
        happyVO.setApprise(happyApprise);

        AmqpSender.sendArgs(happyVO);
        return true;
    }

    @Override
    public List<Appraise> getAppraiseRecords(Long userId, String time) {
        return baseMapper.getAppraiseRecords(userId, time);
    }


}
